import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/router_report.dart';
import 'package:lifecycle/lifecycle.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:screen_ratio_adapter/screen_ratio_adapter.dart';
import 'package:wakelock/wakelock.dart';
import 'package:friends_flutter/routes/app_pages.dart';
import 'package:friends_flutter/utils/common_sp_util.dart';
import 'package:friends_flutter/utils/screens_utils.dart';

import 'config/app_config.dart';
import 'config/app_theme.dart';
import 'config/lang/translation_service.dart';
import 'config/widgets/refresh_footer_view.dart';
import 'config/widgets/refresh_header_view.dart';

void main() {
  FxWidgetsFlutterBinding.ensureInitialized(uiBlueprints: uiSize);

  //捕获异常
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();
    //初始化.0
    await AppConfig.init();
    // 白色沉浸式状态栏颜色  白色文字
    // SystemUiOverlayStyle light = const SystemUiOverlayStyle(
    //   systemNavigationBarColor: Color(0xFF000000),
    //   systemNavigationBarDividerColor: null,
    //   /// 注意安卓要想实现沉浸式的状态栏 需要底部设置透明色
    //   statusBarColor: Colors.transparent,
    //   systemNavigationBarIconBrightness: Brightness.light,
    //   statusBarIconBrightness: Brightness.light,
    //   statusBarBrightness: Brightness.dark,
    // );
    // 黑色沉浸式状态栏颜色 黑色文字
    SystemUiOverlayStyle dark = const SystemUiOverlayStyle(
      systemNavigationBarColor: Colors.transparent,
      systemNavigationBarDividerColor: Colors.transparent,
      /// 注意安卓要想实现沉浸式的状态栏 需要底部设置透明色
      statusBarColor: Colors.transparent,
      systemNavigationBarIconBrightness: Brightness.light,
      statusBarIconBrightness: Brightness.light,
      statusBarBrightness: Brightness.light,
    );
    SystemChrome.setSystemUIOverlayStyle(dark);

    //bug修复 后续可以优化 Theme.of(context).brightness == Brightness.dark
    // if (GetPlatform.isIOS) {
    //   SystemChrome.setSystemUIOverlayStyle(dark);
    // } else if (GetPlatform.isAndroid) {
    //   SystemChrome.setSystemUIOverlayStyle(
    //       const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
    // }
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])  //禁止横屏
        .then((value) {
      runApp(RefreshConfiguration(
        headerBuilder: () => RefreshHeaderView(),
        // 配置默认头部指示器,假如你每个页面的头部指示器都一样的话,你需要设置这个
        footerBuilder: () => RefreshFooterView(),
        headerTriggerDistance: 80.0,
        // 头部触发刷新的越界距离
        springDescription:
        const SpringDescription(stiffness: 170, damping: 16, mass: 1.9),
        // 自定义回弹动画,三个属性值意义请查询flutter api
        maxOverScrollExtent: 100,
        //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
        maxUnderScrollExtent: 0,
        // 底部最大可以拖动的范围
        enableScrollWhenRefreshCompleted: true,
        //这个属性不兼容PageView和TabBarView,如果你特别需要TabBarView左右滑动,你需要把它设置为true
        enableLoadingWhenFailed: true,
        //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
        hideFooterWhenNotFull: false,
        // Viewport不满一屏时,禁用上拉加载更多功能
        enableBallisticLoad: true,
        // 可以通过惯性滑动触发加载更多
        child: const MyApp(),
      ));
    });
  }, (error, stack) {
    print(FlutterErrorDetails(exception: error, stack: stack));
  });
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 启用屏幕常亮
    Wakelock.enable();
    return GestureDetector(
      onTap: () {
        //点击收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: OKToast(
        child: GetMaterialApp(
          title: '弯道王国',
          debugShowCheckedModeBanner: false,
          initialRoute: AppPages.INITIAL,
          getPages: AppPages.getAllRoutS,
          locale: CommonSpUtil.getLanguageType(),//TranslationService.locale,
          fallbackLocale: TranslationService.fallCallback,
          // unknownRoute: GetPage(name: '/notfound', page: () => UnknownRoutePage()),
          translations: TranslationService(),
          /// 国际化配置 代理
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate, //一定要配置,否则iphone手机长按编辑框有白屏卡着的bug出现
          ],
          supportedLocales: const [
            Locale('zh', 'CN'), //设置语言为中文
            // Locale('en', 'US'),
          ],
          builder: FxTransitionBuilder(builder: null),
          navigatorObservers: [GetXRouterObserver(), defaultLifecycleObserver],
          theme: AppThemes.light,
          darkTheme: AppThemes.dark,
        ),
      ),
    );
  }
}

class GetXRouterObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    RouterReportManager.reportCurrentRoute(route);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) async {
    RouterReportManager.reportRouteDispose(route);
  }
}
